package org.jeecg.common.system.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.entity.SysFile;
import org.jeecg.modules.system.model.ExtractorSummaryVo;
import org.jeecg.modules.system.service.ISysFileService;
import org.jsoup.Jsoup;
import org.lionsoul.jcseg.extractor.SummaryExtractor;
import org.lionsoul.jcseg.extractor.impl.TextRankSummaryExtractor;
import org.lionsoul.jcseg.sentence.SentenceSeg;
import org.lionsoul.jcseg.tokenizer.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author scott
 * @since 2018-12-20
 */
@Slf4j
@RestController
@RequestMapping("/sys/common")
public class CommonController {

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Autowired
    private ISysFileService iSysFileService;

    @DeleteMapping(value = "/delete")
    public Result<Object> remove(
            @RequestParam(value = "id") String id
    ) {
        Result<Object> result = new Result<>();
        SysFile dbSysFile = iSysFileService.getById(id);
        if (dbSysFile == null) {
            result.error500("未找到对应实体");
        } else {
            File diskFile = new File(uploadpath + File.separator + dbSysFile.getRelativePath());
            if (diskFile.exists()) {
                diskFile.delete();
            }
            boolean ok = iSysFileService.removeById(id);
            if (ok) {
                result.success("删除成功!");
            }
        }
        return result;
    }

    @PostMapping(value = "/summary")
    public Result<Object> summary(
            @RequestBody ExtractorSummaryVo extractorSummaryVo
            ) {
        Result<Object> result = new Result<>();
        result.setSuccess(false);
        result.setMessage("未获取到内容");
        final int defaultLength = 100;
        String html = extractorSummaryVo.getHtml();
        int length = extractorSummaryVo.getLength();
        try {
            if (StringUtils.isNotEmpty(html)) {
                html = Jsoup.parse(html).text();
                if (StringUtils.isNotEmpty(html)) {
                    //1, 创建Jcseg ISegment分词对象
                    JcsegTaskConfig config = new JcsegTaskConfig(true);
                    //设置过滤停止词
                    config.setClearStopwords(true);
                    //设置关闭同义词追加
                    config.setAppendCJKSyn(false);
                    //设置去除不识别的词条
                    config.setKeepUnregWords(false);
                    ADictionary dic = DictionaryFactory.createSingletonDictionary(config);
                    ISegment seg = SegmentFactory.createJcseg(
                            JcsegTaskConfig.COMPLEX_MODE,
                            new Object[]{config, dic}
                    );

                    //2, 构造TextRankSummaryExtractor自动摘要提取对象
                    SummaryExtractor extractor = new TextRankSummaryExtractor(seg, new SentenceSeg());

                    //3, 从一个Reader输入流中获取length长度的摘要
                    String summary = extractor.getSummary(new StringReader(html), length == 0 ? defaultLength : length);

                    result.setMessage("成功生成摘要");
                    result.setSuccess(true);
                    result.setResult(summary);
                    result.setCode(HttpStatus.OK.value());
                }
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping(value = "/upload")
    public Result<Object> upload(
            HttpServletRequest request,
            @RequestParam(value = "type", defaultValue = "0") Integer type) {
        Result<Object> result = new Result<>();
        try {
            String ctxPath = uploadpath;
            String fileName = null;
            String bizPath = "user";
            String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
            if (!file.exists()) {
                file.mkdirs();// 创建文件根目录
            }
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
            String orgName = mf.getOriginalFilename();// 获取文件名
            fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
            String savePath = file.getPath() + File.separator + fileName;
            String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
            if (dbpath.contains("\\")) {
                dbpath = dbpath.replace("\\", "/");
            }
            File savefile = new File(savePath);

            // 新增文件对象
            SysFile sysFile = new SysFile();
            sysFile.setOriginalFileName(orgName);
            sysFile.setType(type);
            sysFile.setRelativePath(dbpath);
            sysFile.setFileSize(mf.getSize());
            sysFile.setCreateTime(new Date());
            iSysFileService.save(sysFile);

            FileCopyUtils.copy(mf.getBytes(), savefile);

            result = Result.ok(sysFile);
        } catch (IOException e) {
            result.setSuccess(false);
            result.setMessage(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 预览图片
     * 请求地址：http://localhost:8080/common/view/{user/20190119/e1fe9925bc315c60addea1b98eb1cb1349547719_1547866868179.jpg}
     *
     * @param request
     * @param response
     */
    @GetMapping(value = "/view/**")
    public void view(HttpServletRequest request, HttpServletResponse response) {
        // ISO-8859-1 ==> UTF-8 进行编码转换
        String imgPath = extractPathFromPattern(request);
        // 其余处理略
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            imgPath = imgPath.replace("..", "");
            if (imgPath.endsWith(",")) {
                imgPath = imgPath.substring(0, imgPath.length() - 1);
            }
            response.setContentType("image/jpeg;charset=utf-8");
            String localPath = uploadpath;
            String imgurl = localPath + File.separator + imgPath;
            inputStream = new BufferedInputStream(new FileInputStream(imgurl));
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (IOException e) {
            log.info("预览图片失败" + e.getMessage());
            // e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 把指定URL后的字符串全部截断当成参数
     * 这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     *
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }

}
